package com.tmt.im.manager.controller.api;

import com.tmt.im.manager.helper.PrincipalHelper;
import com.tmt.im.manager.helper.QrCodeHelper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.concurrent.CompletableFuture;

/**
 * 二维码相关接口
 *
 * @Description TODO
 * @Author wuyi
 * @Date 2024/8/23 12:04
 * @Version 1.0
 **/
@Slf4j
@Async("asyncTaskExecutor")
@Tag(name = "二维码相关接口", description = "二维码相关接口")
@RestController
@RequestMapping("${api-url-prefix}/qrCode")
public class QrCodeController {

    @Operation(summary = "我的二维码", description = "获取当前用户自己的二维码")
    @GetMapping(value = "/self")
    public CompletableFuture<Void> getQrCodeData(HttpServletResponse response, Principal principal) {
        Long userId = PrincipalHelper.getCurrentUserId(principal);
        _getQrCodeData(userId, response);
        return CompletableFuture.completedFuture(null);
    }

    @Operation(summary = "用户二维码", description = "获取指定用户的二维码")
    @GetMapping(value = "/{userId}")
    public CompletableFuture<Void> getQrCodeUrlByUserId(@PathVariable("userId") Long userId, HttpServletResponse response, Principal principal) {
        _getQrCodeData(userId, response);
        return CompletableFuture.completedFuture(null);
    }

    public void _getQrCodeData(Long userId, HttpServletResponse response) {
        try {
            BufferedImage bufferedImage = QrCodeHelper.getQrCodeData(userId);
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                ImageIO.write(bufferedImage, "PNG", outputStream);
                try (InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray())) {
                    // 清空response
                    response.reset();
                    // 设置response的Header
                    response.setCharacterEncoding("UTF-8");
                    //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
                    //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
                    // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
                    response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(userId + "_qr_code.png", StandardCharsets.UTF_8));
                    // 告知浏览器文件的大小
                    response.addHeader("Content-Length", "" + inputStream.available());
                    response.setContentType("image/png");
                    try (OutputStream output = new BufferedOutputStream(response.getOutputStream())) {
                        output.write(inputStream.readAllBytes());
                        output.flush();
                    }
                }
            }
        } catch (Exception ex) {
        }
    }

}
